<?php


namespace services\base;

use common\helpers\CommonHelper;
use common\helpers\RedisHelper;
use common\models\base\CommonStatus;
use common\components\Service;
use services\log\LogMemberOpService;
use Yii;

class CommonStatusService extends Service
{
    /**
     * 通用选项列表
     * @param int $type
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public function commonStatusList(int $type, int $page, int $pageSize): array
    {
        $query = CommonStatus::find()
            ->where(['type' => $type, 'status' => [CommonStatus::STATUS_ENABLE, CommonStatus::STATUS_INVALID]]);
        $list = $this->getListPageRes($query, $page, $pageSize, ['status' => SORT_DESC, 'sort' => SORT_ASC, 'id' => SORT_DESC]);
        foreach ($list['list'] as &$li) {
            $li['status_name'] = CommonStatus::$statuss[$li['status']];
        }
        return $list;
    }

    /**
     * 获取正常
     * @param int $type
     * @param array|int|null $orIds 绑定IDs【正常+禁用】
     * @return CommonStatus[]
     */
    public static function getEnableListByIds(int $type, $orIds = null): array
    {
        $query = CommonStatus::find()
            ->select(['*'])
            ->where([
                'type' => $type,
                'status' => CommonStatus::STATUS_ENABLE,
            ]);
        if (!is_null($orIds)) {// 编辑查找已绑定选项
            $query->orWhere([
                'id' => $orIds,
                'status' => [CommonStatus::STATUS_INVALID, CommonStatus::STATUS_ENABLE],
            ]);
        }
        return $query->orderBy(['sort' => SORT_ASC, 'id' => SORT_ASC])->all();
    }

    /**
     * @param int $type
     * @return CommonStatus[]
     */
    public static function getNormalListByIds(int $type): array
    {
        $query = CommonStatus::find()
            ->select(['*'])
            ->where([
                'type' => $type,
                'status' => [CommonStatus::STATUS_INVALID, CommonStatus::STATUS_ENABLE],
            ]);
        return $query->orderBy(['sort' => SORT_ASC, 'id' => SORT_ASC])->all();
    }

    /**
     * 获取列表筛选项
     * @return array
     */
    public static function getListCondition(int $type): array
    {
        return CommonHelper::getListCondition(self::getNormalListByIds($type), ['value_column' => 'id', 'label_column' => 'name']);
    }

    /**
     * 获取编辑筛选项
     * @param int $type
     * @param int|array|null $orIds
     * @return array
     */
    public static function getEditCondition(int $type, $orIds = null): array
    {
        return CommonHelper::getListCondition(self::getEnableListByIds($type, $orIds), ['value_column' => 'id', 'label_column' => 'name']);
    }

    /**
     * 基础设置新增/编辑
     * @throws \Exception
     */
    public function updateCommonStatus(array $params)
    {
        $common = new CommonStatus();
        $scenario = 'create';
        $oldCommon = null;
        // 是否为编辑，编辑判断排除当前ID
        $whereId = [];
        if ($params['id']) {
            $whereId = ['!=', 'id', $params['id']];
            // 手机卡表
            $oldCommon = self::getData($params['id']);
            $common = CommonStatus::findOne($params['id']);
            $scenario = 'edit';
        }
        // 判断名称是否存在
        $check = CommonStatus::find()
            ->select(['id'])
            ->where([
                'name' => $params['name'],
                'type' => $params['type'],
                'status' => [CommonStatus::STATUS_ENABLE, CommonStatus::STATUS_INVALID]
            ])
            ->andWhere($whereId)
            ->one();
        if ($check) {
            return CommonHelper::api(422, '名称已存在');
        }
        $common->type = $params['type'];
        $common->name = $params['name'];
        $common->status = $params['status'];
        $common->sort = $params['sort'] ?? 100;
        $common->operation_id = Yii::$app->user->identity->member_id;
        $common->operation_name = Yii::$app->user->identity->member->realname;
        $common->saveAndCheckResult();

        // 添加日志
        LogMemberOpService::createCommonStatusLog($scenario, $common, $oldCommon);
        // 更新缓存
        RedisHelper::setCommonStatus($common);
        return $common->id;
    }

    /**
     * 基础设置数据
     * @param int $id
     * @return CommonStatus|null
     */
    public static function getData(int $id): ?CommonStatus
    {
        return CommonStatus::findOne($id);
    }

    /**
     * 基础设置软删除
     * @throws \Exception
     */
    public function deleteCommonStatus(array $params): array
    {
        // 更新状态为-1
        CommonStatus::updateAll([
            'status' => CommonStatus::STATUS_DELETE,
            'operation_id' => Yii::$app->user->identity->member_id,
            'operation_name' => Yii::$app->user->identity->member->realname,
            'updated_at' => time()
        ], ['id' => $params['id']]);

        // 添加日志
        LogMemberOpService::createCommonStatusLog('delete', self::getData($params['id']));
        // 删除缓存
        RedisHelper::delCommonStatus($params['id']);
        return ['id' => $params['id']];
    }
}
